package tcp

import (
	"errors"
	"fmt"
	"io"
	"net"
	"syscall"
	"time"
)

func NewClient(port int) {
	conn, err := net.Dial("tcp", fmt.Sprintf(":%d", port))
	if err != nil {
		fmt.Printf("dial port:%d failed, err: %v\n", port, err)
		return
	}

	handleClientConn(conn)

}

func handleClientConn(conn net.Conn) {

	for {
		// write msg to server
		msg := "Hello,TCP/IP"
		writeLen, err := conn.Write([]byte(msg))

		if errors.Is(err, syscall.EPIPE) {
			fmt.Print("broken pipe maybe cause by server closed")
			if err := conn.Close(); err != nil {
				fmt.Printf("error close conn, err: %v\n", err)
			}
			return
		}
		if err != nil {
			fmt.Printf("write msg to server err: %v\n", err)
			continue
		}
		fmt.Printf("success write msg: %s to server with len: %d\n", msg, writeLen)

		// recv msg from server
		chunk := make([]byte, 1024)
		readLen, err := conn.Read(chunk)
		if err == io.EOF {
			fmt.Printf("read message from server failed maybe caused by server closed\n")
			continue
		}
		if err != nil {
			fmt.Printf("read from conn err: %v\n", err)
			continue
		}

		fmt.Printf("read from server msg: %s, len: %d\n", chunk[:readLen], readLen)

		time.Sleep(2 * time.Second)
	}
}
